#Get original directory structure
load('directory_structure.RData')

#Create original directories
directories = str_replace(directory_structure, "/[^/]+$", "") %>% 
                str_replace("^[^/]+$", ".") %>% unique %>% sort

for (d in directories[-1]) {
  
  d_list = str_split(d, '/') %>% unlist
  
  for (i in seq_along(d_list)) {
    dir_path = d_list[1:i] %>% paste0(collapse = '/')
    if (!file.exists(file.path(getwd(),dir_path))) {
      dir.create(file.path(getwd(),dir_path))
    }
  }
}

#Move files into place
move_table = data.frame(directory = str_replace(directory_structure, "/[^/]+$", "") %>% 
                                    str_replace("^[^/]+$", "."),
                        file_name = str_extract(directory_structure, "(?<=/|^)[^/]+$")
                        )

for (r in 1:nrow(move_table)) {
  from_file = file.path('.', move_table[r,'file_name'])
  to_file = file.path('.', move_table[r, 'directory'], move_table[r, 'file_name'])
  
  if (move_table[r, 'directory'] != ".") {
    if (file.exists(from_file)) {
      file.copy(from = from_file, to = to_file)
      file.remove(from_file)
    }
  }
}